package com.itheima.project.handler.wechat;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.itheima.project.constant.SuperConstant;
import com.itheima.project.constant.trade.TradingConstant;
import com.itheima.project.core.enums.trade.TradingEnum;
import com.itheima.project.exception.ProjectException;
import com.itheima.project.handler.BeforePayHandler;
import com.itheima.project.handler.JsapiPayHandler;
import com.itheima.project.handler.wechat.client.Config;
import com.itheima.project.handler.wechat.client.Factory;
import com.itheima.project.handler.wechat.config.WechatPayConfig;
import com.itheima.project.handler.wechat.response.JsapiPreCreateResponse;
import com.itheima.project.handler.wechat.response.NativePreCreateResponse;
import com.itheima.project.handler.wechat.response.QueryResponse;
import com.itheima.project.handler.wechat.response.RefundResponse;
import com.itheima.project.pojo.RefundRecord;
import com.itheima.project.pojo.Trading;
import com.itheima.project.service.IRefundRecordService;
import com.itheima.project.service.ITradingService;
import com.itheima.project.utils.BeanConv;
import com.itheima.project.utils.EmptyUtil;
import com.itheima.project.vo.trade.RefundRecordVo;
import com.itheima.project.vo.trade.TradingVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @ClassName WechatJsapiPayHandlerImpl.java
 * @Description Jsapi支付处理
 */
@Service("wechatJsapiPayHandler")
public class WechatJsapiPayHandler implements JsapiPayHandler {

    @Autowired
    WechatPayConfig wechatPayConfig;

    @Autowired
    ITradingService tradingService;

    @Autowired
    IRefundRecordService refundRecordService;

    @Autowired
    IdentifierGenerator identifierGenerator;

    @Autowired
    BeforePayHandler beforePayHandler;

    @Override
    public TradingVo createJsapiTrading(TradingVo tradingVo) throws ProjectException {
        //1.1、交易前置处理：检测交易单参数
        Boolean flag = beforePayHandler.checkeCreateTrading(tradingVo);
        if (!flag){
            throw new ProjectException(TradingEnum.NATIVE_PAY_FAIL);
        }
        //1.2、交易前置处理：幂等性处理
        beforePayHandler.idempotentCreateTrading(tradingVo);
        //2、获得微信客户端
        Config config = wechatPayConfig.queryConfig(tradingVo.getEnterpriseId());
        //3、客户端如果为空，抛出异常
        if (EmptyUtil.isNullOrEmpty(config)){
            throw  new ProjectException(TradingEnum.CONFIG_EMPT);
        }
        Factory.setOptions(config);
        //4、调用微信API：preCreateResponse
        JsapiPreCreateResponse jsapiPreCreateResponse = Factory.jsapiPreCreate(
                String.valueOf(tradingVo.getTradingOrderNo()),
                String.valueOf(tradingVo.getTradingAmount()),
                tradingVo.getMemo(),
                tradingVo.getOpenId());
        //5.1、受理成功：修改交易单
        if (!EmptyUtil.isNullOrEmpty(jsapiPreCreateResponse)){
            String subCode = jsapiPreCreateResponse.getCode();
            String packages = jsapiPreCreateResponse.getPackages();
            //4.1、指定统一下单code
            tradingVo.setPlaceOrderCode(subCode);
            //4.2、指定统一下单返回信息
            tradingVo.setPlaceOrderMsg(packages);
            //4.3、指定统一下单json字符串
            tradingVo.setPlaceOrderJson(JSONObject.toJSONString(jsapiPreCreateResponse));
            //4.4、指定交易状态
            tradingVo.setTradingState(TradingConstant.FKZ);
            //4.5、重新保存信息
            Trading trading = BeanConv.toBean(tradingVo, Trading.class);
            flag = tradingService.saveOrUpdate(trading);
            if (!flag){
                throw new ProjectException(TradingEnum.SAVE_OR_UPDATE_FAIL);
            }
            return BeanConv.toBean(trading, TradingVo.class);
            //5.2受理失败：抛出异常
        }else {
            throw new ProjectException(TradingEnum.NATIVE_PAY_FAIL);
        }
    }
}
